package com.hankol.material.limit;

import android.util.Log;

import com.baselibrary.db.DBManager;
import com.baselibrary.router.ActivityRouter;
import com.baselibrary.utils.TimeUtil;
import com.baselibrary.bean.download.DownloadInfo;
import com.hankol.material.help.MaterialHelp;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by zs
 * Date：2018年 09月 12日
 * Time：13:50
 * —————————————————————————————————————
 * About: 观察者
 * —————————————————————————————————————
 */
public class DownloadLimitObserver implements Observer<DownloadInfo> {

    public Disposable d;//可以用于取消注册的监听者
    public DownloadInfo downloadInfo;

    @Override
    public void onSubscribe(Disposable d) {
        this.d = d;
    }

    @Override
    public void onNext(DownloadInfo value) {
        this.downloadInfo = value;
        downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD);
        EventBus.getDefault().post(downloadInfo);
    }

    @Override
    public void onError(Throwable e) {
        e.toString();
        Log.d("My_Log", "onError");
        if (DownloadLimitManager.getInstance().getDownloadUrl(downloadInfo.getUrl())) {
            DownloadLimitManager.getInstance().pauseDownload(downloadInfo.getUrl());
            downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_ERROR);
            EventBus.getDefault().post(downloadInfo);
        } else {
            if (downloadInfo.getDownloadStatus().equals(DownloadInfo.DOWNLOAD)) {
                downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_PAUSE);
            }
            EventBus.getDefault().post(downloadInfo);
        }
        DBManager.getInstance().updateDownload(downloadInfo);
    }


    @Override
    public void onComplete() {
        Log.d("My_Log", "onComplete");
        if (downloadInfo != null) {
            downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_OVER);
            //下载完成更新本地数据库
            downloadInfo.setTime(TimeUtil.setYearMonthDay(TimeUtil.getCurrentTimeMillis()));
            DBManager.getInstance().updateDownload(downloadInfo);
            EventBus.getDefault().post(downloadInfo);
        }
    }
}
